package com.wlyuan.open.domain.api;

import com.wlyuan.core.domain.valueobj.UserId;
import com.wlyuan.core.marker.NamedStatus;
import com.wlyuan.open.domain.api.assembler.OpenApiAssembler;
import com.wlyuan.open.domain.api.valueobj.Method;
import com.wlyuan.open.domain.api.valueobj.OpenApiId;
import com.wlyuan.open.dto.api.OpenApiUpdateDTO;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Optional;

/**
 * @author lijing
 * @description
 */
@Data
public class OpenApi implements Serializable {
    private static final long serialVersionUID = -3045028503079959916L;

    private OpenApiId id;
    @ApiModelProperty("接口名称")
    private String name;
    @ApiModelProperty("接口地址")
    private String url;
    @ApiModelProperty("请求方式")
    private Method method;
    @ApiModelProperty("状态 0 禁用 1 启用")
    private NamedStatus status;
    @ApiModelProperty("接口描述")
    private String remark;
    @ApiModelProperty("创建时间")
    private LocalDateTime createAt;
    @ApiModelProperty("更新时间")
    private LocalDateTime updateAt;
    @ApiModelProperty("创建人")
    private UserId createBy;
    @ApiModelProperty("更新人")
    private String updateBy;
    private Integer sort;

    public OpenApi disable(String user) {
        this.updateBy = user;
        this.status = NamedStatus.DISABLED;
        this.updateAt = LocalDateTime.now();
        return this;
    }

    public OpenApi enable(String user) {
        this.updateBy = user;
        this.status = NamedStatus.ENABLED;
        this.updateAt = LocalDateTime.now();
        return this;
    }

    public OpenApi change(OpenApiUpdateDTO update) {
        OpenApiAssembler.assemble(this, update);
        this.updateAt = LocalDateTime.now();
        this.updateBy = update.getUser();
        return this;
    }

    public Boolean hasEnable() {
        return Optional.ofNullable(status).map(status -> NamedStatus.ENABLED.equals(status)).orElse(false);
    }
}
